package com.snail.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.snail.constants.RedisConstants;
import com.snail.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author 蔡徐坤
 * @Date 2025/8/18 16:48
 * @Description: TODO
 */
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final RedisTemplate redisTemplate;

    private final JavaMailSender mailSender;

    @Override
    public void sendResetEmail(String email) {
        // 生成随机的6位数验证码
        String code = RandomUtil.randomNumbers(6);
        String EMAIL_PREFIX = RedisConstants.EMAIL_PREFIX+email;
        redisTemplate.opsForValue().set(EMAIL_PREFIX, code, 300L, TimeUnit.SECONDS);
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1605338726@qq.com");
        message.setTo(email);
        message.setSubject("找回密码验证码");
        message.setText("您的验证码是: " + code + "，有效期5分钟。");
        mailSender.send(message);   
    }

    @Override
    public boolean validateResetEmail(String email, String code) {
        String EMAIL_PREFIX = RedisConstants.EMAIL_PREFIX+email;
        Object cacheCode = redisTemplate.opsForValue().get(EMAIL_PREFIX);
        return code.equals(cacheCode);
    }
}
